<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class validate
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle( Request $request, Closure $next )
    {
        // 执行路由
        $execute_router = substr( $request->route()->getAction( 'controller' ), 21 );
        
        // 行为
        $action = explode( '@', $execute_router );

        // 验证数据
        $params = $request->input();

        // 控制器
        $controller = $action[ 0 ];

        // 方法
        $method = $action[ 1 ];

        //自动验证器名
        $validate_class = 'App\Validator\\' . $controller;

        // 存在验证器则自动验证
        if( class_exists( $validate_class ) )
        {
            // 初始化验证器
            $validate = new $validate_class;

            //验证场景
            if( $validate->has_scene( $method ) )
            {
                // 验证信息
                $message = $validate->messages();

                // 验证规则
                $rules = $validate->get_scene_rule( $method );

                // 进行验证
                $result = Validator::make( $params, $rules, $message );

                // 验证失败
                if( $result->fails() )
                {
                    return response()->json( [ 'code' => 10002, 'message' => $result->errors()->first() ] );
                }
            }
        }

        // 验证方法
        return $next( $request );
    }
}
